<template>
  <div class="p-2">
    <!-- 物模型协议 - 品类管理 -->
    <!-- 查询表单 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="品类名称" prop="categoryName">
          <el-input v-model="queryParams.categoryName" placeholder="请输入品类名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="品类编码" prop="categoryKey">
          <el-input v-model="queryParams.categoryKey" placeholder="请输入品类编码" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增品类</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(false)">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange" border fixed>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="品类ID" align="center" prop="categoryId" width="120" />
        <el-table-column label="品类名称" align="center" prop="categoryName" />
        <el-table-column label="品类类型" align="center" prop="categoryType" width="120">
          <template #default="scope">
            <el-tag :type="getCategoryTypeTag(scope.row.categoryType)">
              {{ getCategoryTypeText(scope.row.categoryType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="品类编码" align="center" prop="categoryKey" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="320" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改品类对话框 -->
    <CategoryFormDialog v-model:visible="dialog.visible" :title="dialog.title" :data="form"
      @confirm="handleFormSubmit" />

    <!-- 品类详情对话框 -->
    <CategoryDetailDialog v-model:visible="detailDialog.visible" :data="detailDialog.data" />

    <!-- 属性管理对话框 -->
    <PropertyManageDialog v-model:visible="propertyDialog.visible" :category-id="propertyDialog.categoryId"
      @refresh="getList" />
  </div>
</template>

<script setup name="CategoryManage" lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Search, Refresh, Plus, Edit, Delete, Download, Upload, CopyDocument, View, List, Setting, Bell } from '@element-plus/icons-vue'
import CategoryFormDialog from './components/CategoryFormDialog.vue'
import CategoryDetailDialog from './components/CategoryDetailDialog.vue'
import PropertyManageDialog from './components/PropertyManageDialog.vue'
// 使用本地模拟数据，移除远程API函数导入
import type { CategoryInfo, CategoryQueryParams } from '@/api/IOT/protocolManage/categoryManage/types'

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const categoryList = ref<CategoryInfo[]>([])
const propertyList = ref([])
const selectedRows = ref<CategoryInfo[]>([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  categoryName: '',
  categoryKey: '',
  categoryType: ''
})

// 表单数据
const form = reactive({
  categoryId: '',
  categoryName: '',
  categoryKey: '',
  categoryType: 0,
  description: ''
})

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 属性管理对话框状态
const propertyDialog = reactive({
  visible: false,
  categoryId: ''
})



// 模拟网络延迟（0~1500ms）
const delayRandom = (min = 200, max = 1500) => new Promise(resolve => setTimeout(resolve, Math.floor(Math.random() * (max - min + 1)) + min))

// 本地模拟的品类数据源
const allCategories = ref<CategoryInfo[]>([
  { categoryId: 1001, categoryName: '水泵设备', categoryType: 0, categoryKey: 'pump', status: '1', createTime: '2024-09-01 10:00:00', updateTime: '2024-09-10 12:00:00', description: '水泵类设备', productCount: 3, propertyCount: 12, functionCount: 5, eventCount: 2 },
  { categoryId: 1002, categoryName: '水位传感器', categoryType: 0, categoryKey: 'water_level_sensor', status: '1', createTime: '2024-09-02 09:30:00', updateTime: '2024-09-12 11:20:00', description: '水位检测传感器', productCount: 5, propertyCount: 15, functionCount: 3, eventCount: 1 },
  { categoryId: 1003, categoryName: '视频监控系统', categoryType: 1, categoryKey: 'video_monitor', status: '0', createTime: '2024-09-03 08:20:00', updateTime: '2024-09-15 08:20:00', description: '监控录像与抓拍', productCount: 2, propertyCount: 8, functionCount: 4, eventCount: 2 }
])

// 分类类型文本与标签
const getCategoryTypeText = (type: number) => {
  return Number(type) === 1 ? '业务系统' : '设备'
}
const getCategoryTypeTag = (type: number) => {
  return Number(type) === 1 ? 'success' : 'primary'
}

// 查询品类列表（使用本地模拟数据）
const getList = async () => {
  loading.value = true
  await delayRandom()
  // 过滤
  const { categoryName, categoryKey } = queryParams
  let filtered = allCategories.value
  if (categoryName) {
    filtered = filtered.filter(c => String(c.categoryName).toLowerCase().includes(String(categoryName).toLowerCase()))
  }
  if (categoryKey) {
    filtered = filtered.filter(c => String(c.categoryKey).toLowerCase().includes(String(categoryKey).toLowerCase()))
  }
  // 分页
  const start = (queryParams.pageNum - 1) * queryParams.pageSize
  const end = start + queryParams.pageSize
  categoryList.value = filtered.slice(start, end) as CategoryInfo[]
  total.value = filtered.length
  console.log('执行了');
  loading.value = false
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  queryParams.categoryName = ''
  queryParams.categoryKey = ''
  queryParams.categoryType = ''
  getList()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.categoryId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  dialog.visible = true
  dialog.title = '添加品类'
}

// 修改按钮操作
const handleUpdate = (row?: any) => {
  const categoryId = row?.categoryId || ids.value[0]
  // 模拟获取详情
  const category = categoryList.value.find(item => item.categoryId === categoryId)
  if (category) {
    form.categoryId = category.categoryId
    form.categoryName = category.categoryName
    form.categoryKey = category.categoryKey
    form.categoryType = parseInt(category.categoryType) || 0
  }
  dialog.visible = true
  dialog.title = '修改品类'
}

// 查看详情
const handleView = (row: any) => {
  detailDialog.data = row
  detailDialog.visible = true
}

// 属性管理
const handlePropertyManage = (row: any) => {
  propertyDialog.visible = true
  propertyDialog.categoryId = row.categoryId
}

// 功能管理
const handleFunctionManage = (row: any) => {
  ElMessage.info('跳转到功能管理页面：' + row.categoryName)
}

// 事件管理
const handleEventManage = (row: any) => {
  ElMessage.info('跳转到事件管理页面：' + row.categoryName)
}

// 查看产品
const viewProducts = (row: any) => {
  ElMessage.info('跳转到产品列表页面：' + row.categoryName)
}

// 产品管理
const handleProductManage = (row: any) => {
  // 跳转到产品管理页面，传递品类信息
  ElMessage.success(`跳转到产品管理页面，品类：${row.categoryName}`)
  // 这里可以使用路由跳转到产品管理页面
  router.push({ path: '/iot/protocolManage/productManage', query: { categoryId: row.categoryId, categoryName: row.categoryName } })
}

// 状态修改
const handleStatusChange = (row: any) => {
  const text = row.status === '1' ? '启用' : '停用'
  ElMessageBox.confirm('确认要"' + text + '""' + row.categoryName + '"品类吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success(text + '成功')
  }).catch(() => {
    row.status = row.status === '0' ? '1' : '0'
  })
}

// 复制品类
const handleCopy = () => {
  ElMessage.info('复制品类功能开发中')
}

// 删除按钮操作（使用本地模拟数据）
const handleDelete = async (row?: any) => {
  let categoryIds: number[] = []
  let confirmMessage = ''
  if (row) {
    categoryIds = [row.categoryId]
    confirmMessage = `确定要删除品类"${row.categoryName}"吗？删除后将无法恢复！`
  } else {
    categoryIds = ids.value as number[]
    confirmMessage = `确定要删除选中的 ${categoryIds.length} 个品类吗？删除后将无法恢复！`
  }
  if (categoryIds.length === 0) {
    ElMessage.warning('请选择要删除的品类')
    return
  }
  try {
    await ElMessageBox.confirm(confirmMessage, '删除确认', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await delayRandom()
    allCategories.value = allCategories.value.filter(c => !categoryIds.includes(Number(c.categoryId)))
    ElMessage.success('删除成功')
    // 重置选中状态并刷新
    ids.value = []
    single.value = true
    multiple.value = true
    getList()
  } catch {
    ElMessage.info('已取消删除')
  }
}

// 导出（使用CSV导出本地数据）
const handleExport = async () => {
  await delayRandom()
  const headers = ['品类ID', '品类名称', '品类类型', '品类编码', '状态', '创建时间']
  const rows = categoryList.value.map(c => [c.categoryId, c.categoryName, c.categoryType === 0 ? '设备' : '业务系统', c.categoryKey, c.status === '1' ? '启用' : '停用', c.createTime])
  const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = window.URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `品类列表_${new Date().getTime()}.csv`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)
  ElMessage.success('导出成功')
}

// 导入按钮操作
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 处理表单提交
const handleFormSubmit = async (formData: any) => {
  await delayRandom()
  if (formData.categoryId) {
    // 修改
    const idx = allCategories.value.findIndex(c => Number(c.categoryId) === Number(formData.categoryId))
    if (idx !== -1) {
      allCategories.value[idx] = { ...allCategories.value[idx], ...formData, updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ') }
      ElMessage.success('修改成功')
    } else {
      ElMessage.error('未找到该品类')
      return
    }
  } else {
    // 新增
    const newId = Math.max(...allCategories.value.map(c => Number(c.categoryId))) + 1
    const newItem: CategoryInfo = {
      categoryId: newId,
      categoryName: formData.categoryName,
      categoryKey: formData.categoryKey,
      categoryType: Number(formData.categoryType) || 0,
      status: '1',
      createTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      updateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      description: '',
      productCount: 0,
      propertyCount: 0,
      functionCount: 0,
      eventCount: 0
    }
    allCategories.value.unshift(newItem)
    ElMessage.success('新增成功')
  }
  dialog.visible = false
  reset()
  getList()
}

getList();
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}

.category-icon {
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon-uploader .icon {
  width: 60px;
  height: 60px;
  display: block;
  border-radius: 4px;
}

.icon-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.icon-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.icon-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
}
</style>